package org.cxfexample.interceptor.server;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Set;

import javax.xml.stream.XMLStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.apache.xmlbeans.impl.soap.SOAPMessage;
import org.cxfexample.webservice.contentService.RequestObject;

public class ModifyContentInterceptor extends AbstractSoapInterceptor {

	private Log logger = LogFactory.getLog(this.getClass());
	
	public ModifyContentInterceptor() {
		super(Phase.PRE_INVOKE);
	}

	public void handleMessage(SoapMessage message) throws Fault {
		logger.info("Interceptor id:"+this.getId());
		RequestObject content = message.getContent(RequestObject.class);
		logger.info("content:"+content);
		
		if(content!=null){
			logger.info("content value:"+content.getValue());
			content.setValue("success");
		}
		
		SOAPMessage mess=message.getContent(SOAPMessage.class);
		logger.info("mess:"+mess);
		if(mess!=null){
			logger.info("mess value:"+mess);
		}
		
        Set<Class<?>> formats = message.getContentFormats();
        
        logger.info("print content format");
        logger.info("formats size:"+formats.size());
        int i = 1;
        for(Class<?> format:formats){
        	logger.info(i+ " formats:"+format.toString());
        	i++;
        }
        
        XMLStreamReader xmlreader = message.getContent(XMLStreamReader.class);
        logger.info("xmlreader:"+xmlreader);
        
        InputStream inputStream = message.getContent(InputStream.class);
        logger.info("inputStream:"+this.inputStream2String(inputStream));
        
        //here can change the content value
        List<?> list = message.getContent(List.class);
        logger.info("list size:"+list.size());
        for(Object o:list){
        	if(o instanceof RequestObject){
        		RequestObject request = (RequestObject)o;
        		request.setValue("success");
        	}
        }
	}

	 private String inputStream2String(InputStream is){
		   BufferedReader in = new BufferedReader(new InputStreamReader(is));
		   StringBuffer buffer = new StringBuffer();
		   String line = "";
		   try {
			while ((line = in.readLine()) != null){
			     buffer.append(line);
			   }
		} catch (IOException e) {

			e.printStackTrace();
		}
		   return buffer.toString();
}
}
